#!/usr/bin/python3
# 功能：从一个udp端口(sys.argv[1])读取数据，再发送到其它IP:5600
import sys
import socket

# 检查是否有足够的参数
if len(sys.argv) < 3:
    print(f"参数不足，请加上要转发的目标ip，比如：{sys.argv[0]} 5601 192.168.1.12")
    print("建议只用一个目标ip")
    exit()
#   first_arg = sys.argv[1]
# 创建一个UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 绑定本地端口
local_ip = '0.0.0.0'  # 监听所有接口
local_port = int(sys.argv[1])
sock.bind((local_ip, local_port))

# 目标端口
target_port = 5600
#target_ip = sys.argv[2]

# 播报要转发的目标ip
print(f"--> From {local_ip}:{local_port}")
for i in range( len(sys.argv)-2 ):
    print(f"--> Sent message to {sys.argv[2]}:{target_port}")

try:
    while True:
        # 接收数据
        data, addr = sock.recvfrom(4096)  # buffer size is 4096 bytes
#        sock.sendto(data, (str(sys.argv[2]), target_port))
        for i in range( len(sys.argv)-2 ):
            sock.sendto(data, (str(sys.argv[i+2]), target_port))

except KeyboardInterrupt:
    print("Program terminated by user")
finally:
    sock.close()